extends ColorRect

# 定义信号
signal animation_completed

@onready var balls: Node2D = $balls
var ball_texture = preload("res://others_assets/Grid_spread_transition/png/ball.png")


func _ready() -> void:
	show_scene_grid()


# 场景网格可视化（不创建小球，只绘制网格）
func show_scene_grid() -> void:
	#清除旧小球
	for child in balls.get_children():
		child.queue_free()
	
	# 获取当前视口大小
	var viewport_size = get_viewport_rect().size
	#小球间隔/网格间隔
	var spacing := 25
	# 计算需要的网格线数量（确保覆盖整个视口）
	# ceil()向上取整确保覆盖整个屏幕、
	# +2添加额外边距防止边缘溢出"
	var grid_width = int(ceil(viewport_size.x / spacing)) + 2  
	var grid_height = int(ceil(viewport_size.y / spacing)) + 2

	 #创建小球和动画
	create_balls_with_animation(grid_width, grid_height, spacing)

	# 计算网格物理尺寸
	var physical_width = grid_width * spacing
	var physical_height = grid_height * spacing
	
	# 打印网格信息
	print("当前窗口尺寸: %d x %d "%[viewport_size.x,viewport_size.y])
	print("网格尺寸: %d x %d 像素" % [physical_width, physical_height])
	print("创建了适配网格: %d x %d 线, 间距: %d" % [grid_width, grid_height, spacing])
	print("------------------------------------------------------------------------")

# 创建小球和动画方法
func create_balls_with_animation(grid_width: int, grid_height: int, spacing: int) -> void:
	
	for i in range(grid_width):
		for j in range(grid_height):
			var ball = Sprite2D.new()			
			ball.texture = ball_texture					# 设置贴图
			ball.modulate = Color(0, 0, 0, 1)   		# 设置颜色和透明度
			ball.scale = Vector2(0, 0)  				# 初始不可见
			ball.position = Vector2(i, j) * spacing		# 设置位置
			balls.add_child(ball)

			# 创建序列动画
			var ball_tween = create_tween()
			# 延迟出现
			ball_tween.tween_interval((i+j)*0.03)
			#淡入动画
			ball_tween.tween_property(ball, "scale", Vector2(1,1), 0.5)

	# 计算最长的动画时间
	var max_delay = (grid_width + grid_height - 2) * 0.03
	var total_animation_time = max_delay + 0.5
	
	# 等待动画完成后发送信号
	await get_tree().create_timer(total_animation_time).timeout
	print("动画完成，发送信号")
	emit_signal("animation_completed")






	
	
